import json
import re

from lxml import etree

from PageObjectRequests import base_url
from settings import web_type
from util import http_utils
from util.DataQuery.DbTools import DbTools
from util.g import g
from util.pdfSplit.compress_pdf import CompressPdf
from util.pdfSplit.pdf_split import get_file_oss
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM


class IARdmDesc():
    form_btn_loc = (By.LINK_TEXT, '研究开发与技术创新组织管理情况')
    rdm_desc_loc = (By.CSS_SELECTOR, 'textarea#Jscxgl')
    save_btn_loc = (By.CSS_SELECTOR, 'button#dataEprCycxSave')
    # # # 该页面共有四个附件上传按钮
    # upload_btn1_loc = (By.CSS_SELECTOR, '.box-body div:nth-of-type(1)%s')
    # upload_btn2_loc = (By.CSS_SELECTOR, '.box-body div:nth-of-type(2)%s')
    # upload_btn3_loc = (By.CSS_SELECTOR, '.box-body div:nth-of-type(3)%s')
    # upload_btn4_loc = (By.CSS_SELECTOR, '.box-body div:nth-of-type(4)%s')
    btn1 = '.box-body div:nth-of-type(1) .main'
    btn2 = '.box-body div:nth-of-type(2) .main'
    btn3 = '.box-body div:nth-of-type(3) .main'
    btn4 = '.box-body div:nth-of-type(4) .main'

    css = By.CSS_SELECTOR

    tip_str = " div.title"
    btn_str = " .btnBox a"

    res = None

    def __init__(self, response, driver=None, text=''):
        self.driver = driver
        self.text = text
        self.response = response

    @property
    def class_name(self):
        return self.__class__.__name__

    def upload_file(self):
        if g.need_file is False:
            return True
        if not self.res:
            res_text = self.response.get("text")
            res_tree = etree.HTML(res_text)
            self.tree = res_tree
            detail_url = BM.get_first(res_tree.xpath("//ul[@id='title']/li[3]/a/@href"))
            if not detail_url:
                return False
            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            self.res = http_utils.send_get(detail_url, driver=self.driver)
        text = self.res.get("text")
        tree = etree.HTML(text)
        upload_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/File/upload.do"
        data = {
            # "upload": "",
            "dataId": "",
            "type": "",
            "subType": ""
        }
        material_path = BM.get_material_path()
        rdeaa_res = BM.get_first(tree.xpath("//div[@class='box-body']/div[1]//a"))
        is_rdeaa = self.upload(upload_url, data, rdeaa_res, tree, material_path + "\\rdeaa.pdf", "rdeaa")
        cooperation_res = BM.get_first(tree.xpath("//div[@class='box-body']/div[2]//a"))
        is_cooperation = self.upload(upload_url, data, cooperation_res, tree, material_path + "\\cooperation.pdf", "cooperation")
        iep_res = BM.get_first(tree.xpath("//div[@class='box-body']/div[3]//a"))
        is_iep = self.upload(upload_url, data, iep_res, tree, material_path + "\\iep.pdf", "iep")
        ers_res = BM.get_first(tree.xpath("//div[@class='box-body']/div[4]//a"))
        is_ers = self.upload(upload_url, data, ers_res, tree, material_path + "\\ers.pdf", "ers")
        return (is_rdeaa and is_cooperation and is_iep and is_ers)

    def upload(self, upload_url, data, a_ele, tree, file_path, res_type, size=4):
        if not BM.check_file(file_path, size=size):
            rule_id = BM.get_rule_id(res_type=res_type)
            sql = """
            select * from ent_res_pdf where co_id={} and `year`={} and rule_id={} and web_type='{}'
            """.format(g.co_id, g.year, rule_id, web_type)
            data = DbTools.get_hitech_record_by_sql(sql=sql)
            if not data or not data.get("oss_path"):
                return
            oss_path = data.get("oss_path")
            oss_file = get_file_oss(oss_path=oss_path, local_path=file_path + ".pdf")
            BM.wait_file(file_path=oss_file)
            CompressPdf(file_path=oss_file, max_size=size).compress()
            BM.wait_file(file_path=file_path)
        onclick = a_ele.attrib.get("onclick")
        href = a_ele.attrib.get("href")
        if "javascript:void(0);" not in href and "javascripe:void(0);" not in href:
            g.logger.info("附件已上传: {}".format(file_path))
            return True
        a_id_pattern = ".*?'(.*?)'.*?"
        a_id_res = re.findall(a_id_pattern, onclick)
        a_id = BM.get_first(a_id_res)
        onchange = BM.get_first(self.tree.xpath("//input[@id='{}']/@onchange".format(a_id)))
        onchange = onchange.replace("handleFile(this,", "").replace(")", "").replace("'", "").replace("\"", "")
        # data_id_res = re.findall(".*?'((?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9].*?)'.*?", onchange)
        data["dataId"] = BM.get_first(onchange.split(",")[0].strip())
        # type_res = re.findall(".*?,'(\d+)',.*?", onchange)
        data["type"] = BM.get_first(onchange.split(",")[1].strip())
        # sub_type_res = re.findall(".*?,'(\d+[_]+\d+)'", onchange)
        data["subType"] = BM.get_first(onchange.split(",")[2].strip())
        res = http_utils.send_post(url=upload_url, data=data, file_path=file_path, file_key="upload", driver=self.driver)
        text = res.get("text")
        text_j = json.loads(text)
        id_str = text_j.get("id")
        if id_str:
            return True
        else:
            return False

    def fill_form(self):
        res_text = self.response.get("text")
        res_tree = etree.HTML(res_text)
        # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        detail_url = BM.get_first(res_tree.xpath("//ul[@id='title']/li[3]/a/@href"))
        type_res = BM.get_first(res_tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_type']/@value"))
        if not detail_url:
            return False
        detail_url = detail_url if detail_url.startswith("https://") else \
            base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
        res = http_utils.send_get(detail_url, driver=self.driver)
        self.res = res
        add_url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEprCycx.do"
        data = {
            "dataeprcycx.id": "",
            "dataInnocom.id": "",
            "dataEprCycx.dataId": "",
            "dataEprCycx.entId": "",
            "subType": "",
            "type": "",
            "struts.token.name": "token",
            "token": res.get("token"),
            "dataEprCycx.createDate": "",
            "dataEprCycx.Cjscxgl": self.text,
        }
        text = res.get("text")
        tree = etree.HTML(text)
        self.tree = tree
        cycx_id_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.id']/@value"))
        id_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataInnocom.id']/@value"))
        dataId_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.dataId']/@value"))
        entId_res = BM.get_first(tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycx.entId']/@value"))
        subType_res = BM.get_first(
            tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_subType']/@value"))
        createDate_res = BM.get_first(
            tree.xpath("//form[@id='dataEprCycxForm']/input[@id='dataEprCycxForm_dataEprCycx_createDate']/@value"))
        data["dataeprcycx.id"] = cycx_id_res
        data["dataInnocom.id"] = id_res
        data["dataEprCycx.dataId"] = dataId_res
        data["dataEprCycx.entId"] = entId_res
        data["subType"] = subType_res
        data["type"] = type_res
        data["dataEprCycx.createDate"] = createDate_res

        res = http_utils.send_post(add_url, data=data, driver=self.driver)
        message = res.get("message")
        g.logger.info("研究开发与技术创新组织管理情况 上传结果: {}".format(message))
        if u"成功" in message:
            return True
        else:
            return False


if __name__ == '__main__':
    a = IARdmDesc
    # print((a.css, a.btn1 + a.btn_str))
    print((a.css, a.btn1 + a.tip_str))
    # b = (a.upload_btn1_loc[1] + a.tip_str)
    # c = a.upload_btn1_loc[1] + a.btn_str
    # print(a.upload_btn1_loc % a.tip_str)
    # print(b)
    # print(c)
